import { watch, type Directive } from 'vue';
import { useUserStoreHook } from '@/store/modules/user';

/** 权限指令，和权限判断函数 checkPermission 功能类似 */
export const permission: Directive = {
	mounted(el, binding) {
		const { value: permissionRoles } = binding;
		const { roles } = useUserStoreHook();
		if (Array.isArray(permissionRoles) && permissionRoles.length > 0) {
			const hasPermission = roles.some((role) => permissionRoles.includes(role));
			// hasPermission || (el.style.display = "none") // 隐藏
			hasPermission || el.parentNode?.removeChild(el); // 销毁
		} else {
			throw new Error(`need roles! Like v-permission="['admin','editor']"`);
		}
	},
};

// todo 添加响应式更新
/**
 * 权限指令用于动态控制元素的显示基于用户权限
 * 它通过监听用户角色变化来决定元素是否应该被显示
 */
export const permissionWatch: Directive = {
	mounted(el, binding) {
		const { value: permissionRoles } = binding; // 获取指令代码的权限列表

		// 开发环境错误提示
		if (process.env.NODE_ENV !== 'production') {
			if (!Array.isArray(permissionRoles) || permissionRoles.length === 0) {
				console.error("v-permission expects a non-empty array of roles. Example: v-permission=\"['admin','editor']\"");
			}
		}

		// 初始检查
		checkPermission(el, permissionRoles);

		// 响应式监听用户角色变化
		const userStore = useUserStoreHook();
		const stopWatcher = watch(
			() => userStore.roles,
			() => checkPermission(el, permissionRoles),
			{ deep: true }
		);

		// 保存清理函数到元素实例
		el._permissionCleanup = () => {
			stopWatcher();
			delete el._permissionCleanup;
		};
	},
	updated(el, binding) {
		// 权限参数更新时重新检查
		checkPermission(el, binding.value);
	},
	beforeUnmount(el) {
		// 组件卸载前清理监听
		el._permissionCleanup?.();
	},
};
function checkPermission(el: HTMLElement, permissionRoles: string[]) {
	const { roles } = useUserStoreHook(); // 登录用户的权限列表

	// 生产环境静默处理无效配置
	if (!Array.isArray(permissionRoles)) {
		el.style.display = 'none';
		return;
	}

	const hasPermission = roles.some((role) => permissionRoles.includes(role));

	// 显式条件判断
	if (!hasPermission) {
		el.style.display = 'none'; // 隐藏元素
	} else {
		el.style.display = ''; // 恢复显示
	}
}
